//
//  UIViewControllerAdditions.m
//  ColorRecall
//
//  Created by xuanqiang on 12-11-8.
//  Copyright (c) 2012年 Ecpalm. All rights reserved.
//

#import "UIViewControllerAdditions.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIView (LLView)

/**
 ** lineView:       需要绘制成虚线的view
 ** lineLength:     虚线的宽度
 ** lineSpacing:    虚线的间距
 ** lineColor:      虚线的颜色
 **/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
}

@end
@implementation UIViewController(UIViewControllerAdditions)
- (BOOL)isCheckHavViewController:(NSString *)className {
    for (UIViewController *v in  self.navigationController.viewControllers) {
        if ([v isKindOfClass:NSClassFromString(className)]) {
            return YES;
        }
    }

    return NO;
    
}
- (UIViewController *)getCurrentViewController
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

- (void)showLeftButtonImageName:(NSString *)imageName selector:(SEL)sel {
    [self showLeftBarButttonItem:nil image:imageName selector:sel navItem:self.navigationItem];
//    UIBarButtonItem *left =   [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:imageName] renderOrigin] style:UIBarButtonItemStyleDone target:self action:sel];
//    UIImage *image = [UIImage imageNamed:imageName];
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40,40)];
//    [button setImage:image forState:UIControlStateNormal];
//    if(sel){
//        [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
//    }
//    self.navigationItem.leftBarButtonItem =left;// [[UIBarButtonItem alloc] initWithCustomView:button];
//    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:LDAutoFont(18), NSFontAttributeName,nil] forState:UIControlStateNormal];
}

- (void)popSelf:(UIViewController *)selfVc pushViewController:(UIViewController *)toController {
    [self popSelf:selfVc pushViewController:toController animation:YES];
}
- (void)popSelf:(UIViewController *)selfVc pushViewController:(UIViewController *)toController animation:(BOOL)animation {
    NSMutableArray *vcArray = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    // 获取档期控制器在路由的位置
    int index = (int)[vcArray indexOfObject:selfVc];
    // 移除当前路由器
    [vcArray removeObjectAtIndex:index];
    // 添加新控制器
    [vcArray addObject: toController];
    toController.hidesBottomBarWhenPushed = YES;
    [self.navigationController setViewControllers:vcArray animated:animation];
}
//- (UIView *)showLeftLabelBarButttonItem:(NSString *)title image:(NSString *)imageName selector:(SEL)sel  {
//    if(!sel){
//           sel = @selector(backActionForNavigation:);
//       }
//    return [UIBarButtonItem qmui_itemWithImage:<#(nonnull UIImage *)#> target:<#(nullable id)#> action:<#(nullable SEL)#>]
//    ;[UIBarButtonItem itemWithTarget:self action:sel title:title image:  UIImageMake(imageName)];
//    CGFloat w = [title getTextWidth:44 font:LDAutoFont(14)];
//    if (title) {
//        w = MAX(40, w);
//    }
//    CGFloat www = RatioWidth(100);
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, 40)];
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, w>www?www:w,40)];
////    button.backgroundColor = RedColor;
//    [view addSubview:button];
//
//    [button setTitleColor:[UIColor whiteColor] forState:0];
//    [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
//    button.titleLabel.font = LDAutoFont(14);
//    button.titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
//    [button setTitle:title forState:0];
//
//    if (imageName) {
//        UIImage *image = [UIImage imageNamed:imageName];
//        [button setImage:image forState:0];
//        w = w + RatioWidth(15);
//        w = MAX(40, w);
//        button.frame = CGRectMake(0, 0, w>www?www:w, 44);
//        if (title && imageName) {
//            [button imageOnTheTitleRightWithSpace:5];
//        }
//    }
//    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    button.left = RatioWidth(13);
//    view.width = button.width+RatioWidth(13);
//    [button setEnlargeEdge:10];
//
//    return view;
//}
- (void)showLeftLabelBarButttonItem:(NSString *)title image:(NSString *)imageName selector:(SEL)sel navItem:(UINavigationItem *)item {
    
    UIView *view = [self showLeftLabelBarButttonItem:title image:imageName selector:sel];
    if (item == nil) {
        item = self.navigationItem;
    }
    item.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    
}

- (UIButton *)viewControllerCreateButtonLeftItem:(NSString *)title image:(NSString *)imageName selector:(SEL)sel{
    CGFloat w = [title getTextWidth:44 font:TGAutoFont(14)];
    if (title) {
        w = MAX(40, w);
    }
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, w>110?110:w,30)];
    [button setTitle:title forState:0];
    if(!sel){
        sel = @selector(backActionForNavigation:);
    }
    [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = TGAutoFont(16);
    if (imageName) {
        UIImage *image = [UIImage imageNamed:imageName];
        [button setImage:image forState:0];
        w = w + 25;
        w = MAX(40, w);
        button.frame = CGRectMake(0, 0, w>100?100:w, 44);
        if (title && imageName) {
            [button imageOnTheTitleRightWithSpace:5];
        }
    }
    [button setTitleColor:[UIColor whiteColor] forState:0];

    [button setEnlargeEdge:8];
    return button;
}
- (void)showLeftBarButttonItem:(NSString *)title image:(NSString *)imageName selector:(SEL)sel navItem:(UINavigationItem *)item {

//    UIButton *button = [self viewControllerCreateButtonLeftItem:title image:imageName selector:sel];
    
//    if (item == nil) {
//        item = self.navigationItem;
//    }
//    item.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:sel image:[UIImage imageNamed:imageName]];// [[UIBarButtonItem alloc] initWithCustomView:button];///
    //[UIBarButtonItem itemWithTarget:self action:sel image:[UIImage imageNamed:imageName]];//
//    button.width = 50;
//    item.leftBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:button]];
    

//    CGFloat w = [title getTextWidth:44 font:LDAutoFont(18)];
//    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, w>110?110:w,44)];
//    button.showsTouchWhenHighlighted=YES;
//    [button setTitle:title forState:0];
//    [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
//    button.titleLabel.font = LDAutoFont(16);
//    if (imageName) {
//        UIImage *image = [UIImage imageNamed:imageName];
//        [button setImage:image forState:0];
//        w = w + 20;
//        button.frame = CGRectMake(0, 0, w>110?110:w, 44);
//        [button imageOnTheTitleRightWithSpace:1];
//
//    }
//    [button setTitleColor:[UIColor whiteColor] forState:0];
//    if (item == nil) {
//        item = self.navigationItem;
//
//    }
//    item.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

}
- (void)showLeftBarButttonItem:(NSString *)title selector:(SEL)sel navItem:(UINavigationItem *)item {
    [self showLeftBarButttonItem:title image:nil selector:sel navItem:item];
}
- (void)showLeftBarButttonItem:(NSString *)title selector:(SEL)sel {
    [self showLeftBarButttonItem:title selector:sel navItem:self.navigationItem];
    
}
- (void)showRightBarButtonTitle:(NSString *)title selector:(SEL)sel {
    [self showRightBarButtonItem:nil title:title selector:sel navItem:self.navigationItem];
}
- (void)showRightBarButtonItem:(NSString *)imageName selector:(SEL)sel {
    [self showRightBarButtonItem:imageName title:nil selector:sel navItem:self.navigationItem];
}
- (UIBarButtonItem *)getLeftItem {
    UIView *rith = self.navigationItem.leftBarButtonItem.customView;
    if (!rith) {
        NSArray *items = self.navigationItem.leftBarButtonItems;
        if (items.count>0) {
            return [items lastObject];
        }else {
            return self.navigationItem.leftBarButtonItem;
        }
    }
    return self.navigationItem.leftBarButtonItem;
}
- (UIBarButtonItem *)getRightItem {
    UIView *rith = self.navigationItem.rightBarButtonItem.customView;
    if (!rith) {
        NSArray *items = self.navigationItem.rightBarButtonItems;
        if (items.count>0) {
            return [items lastObject];
        }else {
            return self.navigationItem.rightBarButtonItem;
        }
    }
    return self.navigationItem.rightBarButtonItem;
}
- (void)showRightBarButtonItem:(NSString *)imageName title:(NSString *)title selector:(SEL)sel {
    [self showRightBarButtonItem:imageName title:title selector:sel navItem:self.navigationItem];
}

- (void)showLeftBarButtonTitle:(NSString *)title selector:(SEL)sel {
    
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:sel title:title];
//    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:LDAutoFont(15), NSFontAttributeName,nil] forState:UIControlStateNormal];
}

//- (UIBarButtonItem *)getItemImage:(NSString *)imageName selector:(SEL)sel {
//    return [UIBarButtonItem itemWithTarget:self action:sel image:kImage(imageName)];
//}

//- (void)showRightBarbBlackButtonTitle:(NSString *)title selector:(SEL)sel  {
//    UIBarButtonItem *right = [UIBarButtonItem itemWithTarget:self action:sel title:title font:nil titleColor:[UIColor blackColor] highlightedColor:nil titleEdgeInsets:UIEdgeInsetsZero];
//    self.navigationItem.rightBarButtonItem = right;
//    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:LDAutoFont(15), NSFontAttributeName,nil] forState:UIControlStateNormal];
//
//}
- (void)showRightBarButtonItem:(NSString *)imageName title:(NSString *)title selector:(SEL)sel navItem:(UINavigationItem *)item{
//
//    UIBarButtonItem *right ;
//    
//    if (imageName && title) {
//        right  = [UIBarButtonItem itemWithTarget:self action:sel title:title image:imageName ];//;
//    }else{
//        if (imageName) {
//            right  =  [UIBarButtonItem itemWithTarget:self action:sel image:kImage(imageName)];//;
//        }else {
//            right = [UIBarButtonItem itemWithTarget:self action:sel title:title];
//        }
//    }
//  
//    item.rightBarButtonItem = right;
//    [item.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:LDAutoFont(15), NSFontAttributeName,nil] forState:UIControlStateNormal];
//    right.tintColor = [UIColor whiteColor];
}
- (void)setTitleForNavigation:(NSString *)title {
  UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
  titleLabel.backgroundColor = [UIColor clearColor];
  titleLabel.textAlignment = NSTextAlignmentCenter;
  titleLabel.textColor = [UIColor whiteColor];
  titleLabel.font = [UIFont boldSystemFontOfSize:20];
  titleLabel.text = title;
  [titleLabel sizeToFit];
  self.navigationItem.titleView = titleLabel;
}

- (UIBarButtonItem *)newUIBarButtonItem:(UIImage*)image title:(NSString*)title width:(CGFloat)width selector:(SEL)sel{
  UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width > 0 ? width : image.size.width, image.size.height)];
  button.showsTouchWhenHighlighted=YES;
  [button setBackgroundImage:image forState:UIControlStateNormal];
  if(title){
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, button.frame.size.width, button.frame.size.height)];
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.text = title;
    titleLabel.tag = 1;
    [button addSubview:titleLabel];
  }
   if(sel){
     [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
   }
   return [[UIBarButtonItem alloc] initWithCustomView:button];
}

- (void)setLeftButtonForNavigation:(NSString *)imageName title:(NSString*)title selector:(SEL)sel{
    if (!imageName) {
        imageName = @"fanhui.png";
    }
    if(!title){
        title = @"返回";
    }
  if(!sel){
    sel = @selector(backActionForNavigation:);
  }
  UIImage *image = [UIImage imageNamed:imageName];
  image = [image stretchableImageWithLeftCapWidth:15 topCapHeight:15];
  CGFloat width = 0;
  if(title){
      UIFont *font = [UIFont systemFontOfSize:16];
      NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
      CGSize strSize;
      strSize= [title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX,30) options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:nil].size;
//    CGSize size = [title sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(CGFLOAT_MAX, 30)];
    width = fmaxf(strSize.width+20, 52.0);
  }
  self.navigationItem.leftBarButtonItem = [self newUIBarButtonItem:image title:title width:width selector:sel];
  UILabel *titleLabel = (UILabel *)[self.navigationItem.leftBarButtonItem.customView viewWithTag:1];
  titleLabel.frame = CGRectMake(5, titleLabel.frame.origin.y, titleLabel.frame.size.width, titleLabel.frame.size.height);
}

- (void)setRightButtonForNavigation:(NSString *)imageName title:(NSString*)title selector:(SEL)sel{
  if (!imageName) {
    imageName = @"roundanniu.png";
  }
  UIImage *image = [UIImage imageNamed:imageName];
  image = [image stretchableImageWithLeftCapWidth:15 topCapHeight:15];
  CGFloat width = 0;
  if(title){
      UIFont *font = [UIFont systemFontOfSize:16];
      NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
      CGSize strSize;
      strSize= [title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX,30) options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:nil].size;
      width = fmaxf(strSize.width+10, 52.0);
  }
  self.navigationItem.rightBarButtonItem = [self newUIBarButtonItem:image title:title width:width selector:sel];
}
- (UIBarButtonItem *)newLeftUIBarButtonItem:(NSString *)imageName  isArrow:(BOOL)flag selector:(SEL)sel{
    NSString *imageN =@"";
    if (flag) {
        imageN = @"fanhui.png";
    }else{
        imageN = @"roundanniu.png";
    }
    UIImage *img = [UIImage imageNamed:imageN];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
    
    button.showsTouchWhenHighlighted=YES;
    [button setBackgroundImage:img forState:UIControlStateNormal];
    UILabel * label = [[UILabel alloc] initWithFrame:button.bounds];
    label.backgroundColor =[UIColor clearColor];
    label.textColor =[UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:15];
    label.text = imageName;
    
    [button addSubview: label];
    if(sel){
        [button addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    }
    if (flag) {
        label.frame = CGRectMake(10, label.frame.origin.y, label.frame.size.width-10, label.frame.size.height);
    }
    return [[UIBarButtonItem alloc] initWithCustomView:button];
    
}
- (void)setLeftButtonForNavigation:(NSString *)titleName isArrow:(BOOL)flag selector:(SEL)sel{
    
    if(!sel){
        sel = @selector(backActionForNavigation:);
    }
    self.navigationItem.leftBarButtonItem = [self newLeftUIBarButtonItem:titleName isArrow:flag selector:sel];
}

- (void)backActionForNavigation:(id)sender {
  [self.navigationController popViewControllerAnimated:YES];
}

@end
